package com.zzw.controller;

import com.github.pagehelper.PageInfo;
import com.zzw.bean.Msg;
import com.zzw.bean.Product;
import com.zzw.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 跳转到商品列表页面
     */
    @GetMapping("/list")
    public String list() {
        return "product/list";
    }

    /**
     * 获取商品列表数据
     */
    @ResponseBody
    @GetMapping("/getData")
    public Msg getData(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "productCode", required = false) String productCode,
            @RequestParam(value = "productName", required = false) String productName,
            @RequestParam(value = "categoryId", required = false) Integer categoryId,
            @RequestParam(value = "status", required = false) Integer status) {

        Map<String, Object> params = new HashMap<>();
        params.put("productCode", productCode);
        params.put("productName", productName);
        params.put("categoryId", categoryId);
        params.put("status", status);

        PageInfo<Product> pageInfo = productService.getProductList(params, pageNum, pageSize);
        return Msg.success().add("pageInfo", pageInfo);
    }

    /**
     * 添加商品
     */
    @ResponseBody
    @PostMapping("/add")
    public Msg add(@RequestBody Product product) {
        int result = productService.addProduct(product);
        if (result > 0) {
            return Msg.success();
        } else {
            return Msg.fail("添加商品失败");
        }
    }

    /**
     * 修改商品
     */
    @ResponseBody
    @PutMapping("/update")
    public Msg update(@RequestBody Product product) {
        int result = productService.updateProduct(product);
        if (result > 0) {
            return Msg.success();
        } else {
            return Msg.fail("修改商品失败");
        }
    }

    /**
     * 删除商品
     */
    @ResponseBody
    @DeleteMapping("/delete/{id}")
    public Msg delete(@PathVariable Integer id) {
        int result = productService.deleteProduct(id);
        if (result > 0) {
            return Msg.success();
        } else {
            return Msg.fail("删除商品失败");
        }
    }

    /**
     * 获取商品详情
     */
    @ResponseBody
    @GetMapping("/detail/{id}")
    public Msg detail(@PathVariable Integer id) {
        Product product = productService.getProductById(id);
        if (product == null) {
            return Msg.fail("商品不存在");
        }
        return Msg.success().add("product", product);
    }
}
